package pt.uc.dei.mse.eai.screenScrapping;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Facade around the Java regular expression utility functions.
 * @author XPTS929
 *
 */
public class RegexUtils {

	/**
	 * 
	 * @param what
	 * 		The regex pattern to found
	 * @param where
	 * 		The string where to search in
	 * @return
	 * 		All the first group match of all matches found
	 */
	public List<String> find(String what, String where) {

		Pattern pattern = Pattern.compile(what,
				java.util.regex.Pattern.MULTILINE);

		Matcher matcher = pattern.matcher(where);

		List<String> matches = new ArrayList<String>();
		while (matcher.find()) {
			String found = where.substring(matcher.start(), matcher.end());
			matches.add(found);
		}

		return matches;
	}

	/**
	 * 
	 * @param what
	 * 		The regex pattern to found
	 * @param where
	 * 		The string where to search in
	 * @return
	 * 		A List containing, for each match, all the groups found in it 
	 */
	public List<List<String>> findWithGroups(String what, String where) {

		Pattern pattern = Pattern.compile(what,
				java.util.regex.Pattern.MULTILINE);

		Matcher matcher = pattern.matcher(where);

		List<List<String>> matches = new ArrayList<List<String>>();
		while (matcher.find()) {
			List<String> newGroup = new ArrayList<String>();
			matches.add(newGroup);
			for (int i = 0; i <= matcher.groupCount(); i++) {
				String groupStr = matcher.group(i);
				newGroup.add(groupStr);
			}
		}

		return matches;
	}

}
